/*
*
* 一个用于加载重构后三维项目的启动文件index.js
*
* Daniel
* 2018.03.02
*
* */
define([
    "data",
    "world",
    "cachemodel",
    "CanvasRenderer",
    "Projector",
    "cameraControl",
    "pick",
    "CameraMove",
    "Measure",
    "Signer",
    "cliping",
    "ShowOpacity",
    "material",
    "cameraMark",
    "Disassemble",
    "Region",
    "flie",
    "hawkeye",
    "AddAttr",
    ],
    function(
        data,World,cachemodel,CanvasRenderer,Projector,
        CameraControl,Picks,CameraMove,Measure,
        Signer,Cliping,ShowOpacity,Material,
        CameraMark,Disassemble,Region,Flie,Hawkeye,addAttr
    ){
    
    var API = {
        
        //切换视角
        changeCamera: "",
        
        //拾取
        operationPick: "",
        
        //相机移动动画
        flyTo:"",
        
        //测量
        measure:"",
        
        //标记
        singer:"",
        
        //标记取消
        singerCancal:"",
        
        //标记重做
        singerRedo:"",
    
        //提取标记
        parseSinger:"",
        
        //剖切
        clip:"",
        
        //透明度
        opacity:"",                 //设置透明度
        MoreOpacity:"",                 //设置场景透明度
        
        reopacity:"",           //恢复透明度
    
        showHideModel:"",           //模型显/隐
        
        showModel:"",           //模型显示
        
        bodyColor:"",           //更改构件颜色
    
        getNameModel:"",           //查找模型
        newGroup:"",           //查找模型
        
        frame:"",           //线框显示
    
        resetFrame:"",           //重置线框
    
        viewPlane:"",           //查看平面图层
    
        hidePlane:"",           //隐藏平面图层
        
        removePlane:"",           //移除平面图层
    
        changeColor:"",           //更改背景色
        
        changeHabit:"",           //鼠标习惯更改
        
        quarantine:"",           //隔离
        
        saveMark:"",            //保存书签
        
        parseMark:"",           //恢复书签
    
        image:"",               //截图
        
        twinkle:"",               //闪烁
    
        scaleplate:"",               //计算
        
        location:"",               //定位
    
        dismantle:"",               //分解
    
        redismantle:"",               //分解还原
    
        slide:"",               //层间滑动
        
        resetSlide:"",               //重置层间滑动
    
        materialMap:"",               //贴图管理器
    
        load:"",                       //加载模型
    
        modelDatas:"",                       //模型数据
        
        modelAtrr:"",                       //模型自定义关联
    
        GraphicBox:"",                       //二维涂鸦框
    
        graphicWindows:"",                       //弹出二维涂鸦框
        
        off:"",                       //列表控制器
        offReset:"",                       //重置列表控制器
    
        reset:"",           //重置场景
    
        init:"",           //初始化
        
        body:"",           //当前拾取模型
        DB:"",              //本地数据库
        
        
    };
    //初始化参数
        var container,ApiData, cache, world, control, controleye, pick, addattr, cameraMove, measure, singer, cliping, showOpacity, material,
            cameraMark, disassemble, region, hawkeye, transfrom, flie,scope;
    
    //初始化
        function _init(){
            container = {};
             ApiData = {
                dimension:"",               //控制双击事件
                pickEnable:true,            //控制拾取
                skip:function (jsonData) {},                       //三维数据跳转（用于二维涂鸦）
            };
             cache = new cachemodel();                           //本地数据库
             world = new World();                                //三维场景
             control = new CameraControl();                      //相机控制器
             controleye = new CameraControl();                      //相机控制器
             pick = new Picks();                                 //拾取
             addattr = new addAttr();                                 //拾取
             cameraMove = new CameraMove();                      //相机移动
             measure = new Measure();                            //测量
             singer = new Signer();                              //标记
             cliping = new Cliping();                            //剖面
             showOpacity = new ShowOpacity();                    //显隐
             material = new Material();                          //材质
             cameraMark = new CameraMark();                      //视角书签
             disassemble = new Disassemble();                    //分解模型
             region = new Region();                              //框选模型
             hawkeye = Hawkeye;                            //鹰眼视角
             transfrom = new THREE.TransformControls();          //变换
             flie = Flie;          //文件提取
             scope = API;
        }
        _init();            //默认初始化
        
    /***
     *
     * 对外公共接口API
     * */
    //
    
    // 切换相机
    API.changeCamera = function(){
        control.freeCamera()();
        return this;
    };
    
    //监听拾取
    API.operationPick = function(event){
        if(event.ctrlKey)return;
        pick.flexoPick()(event);
        if(API.body){
           // Vm.treeStruct(API.body.name,API.body.parent.name);       //模型树
            //if(event.type == "mouseup" && Vm.other.areaLayer)Vm.viewAreaLayer(API.body.name,API.body.parent.name);   //区域图层
        }
        return this;
    };
    
    //相机移动
    API.flyTo = function(){
        var object = pick.temporary;
        if(API.downflie){
            var exporter = new THREE.OBJExporter();
            // var jsonData = JSON.stringify(exporter.parse( object ));
            var jsonData = exporter.parse( object );
            
            //输出测试数据
            flie.saveString(jsonData,"model.obj");
            
            if(ApiData.skip!==undefined)ApiData.skip(jsonData);
        }else{
            if(object)cameraMove.cameraMoving()(object);
        }
        
        return this;
    };
    
    
    
    
    //模型定位
    API.location = function(key,fly){
        var keys = key;
        if(keys.length>0){
            var i = 0;
            var length = keys.length;
            for(; i<length;i++){
                var object = world.modelGroup[""+keys[i]+""];
                if(object){
                    pick.oneModel(object);
                    if(length == 1 )cameraMove.cameraMoving()(object);
                }
            }
        }else{
            for(var j = world.modelArray.length-1; j >-1 ; j-- ){
                var project = world.modelArray[j];
                pick.lightModel(project,fly);
            }
        }
        return API;
    };
    
    //测量划线
    API.measure = function (boolean) {
        if (boolean){
            measure.mesureFlag = true;
            container.removeEventListener("mousedown",API.operationPick,false);
            container.addEventListener("mousemove",API.measureEvent.start,false);
            container.addEventListener("mousedown",API.measureEvent.end,false);
            container.addEventListener("mouseup",API.measureEvent.end,false);
        
        }else {
            measure.mesureFlag = false;
            container.addEventListener("mousedown", API.operationPick, false);
            container.removeEventListener("mouseup",API.measureEvent.end,false);
            container.removeEventListener("mousedown",API.measureEvent.end,false);
            container.removeEventListener("mousemove",API.measureEvent.start,false);
            measure.removeMesure()();
        }
        return API;
        
    };
    
    //显示二维涂鸦框
    API.GraphicBox = function (boolean) {
        if(boolean == undefined)return;
        ApiData.dimension = boolean;
        return API;
    };
    
    //跳转二维界面
    API.graphicWindows = function(fun){
            ApiData.skip  = fun;
        return API;
        };
    
    //控制列表
    API.off = function (keys,boolean) {
        if(keys.length>0){
            var i = 0;
            var length = keys.length;
            for(; i<length;i++){
                var object = world.modelGroup[""+keys[i]+""];
                if(object){
                   object.visible = boolean;
                }
            }
        }
    };
    API.offReset = function () {
        for(var j = world.modelArray.length-1; j >-1 ; j-- ){
            var project = world.modelArray[j];
            project.visible = true;
        }
    };
    
    
    
    
    
    //绘制标记
    API.singer = function (boolean) {
            if (boolean){
                //屏蔽三维控制、激活标记
                API.baseEvent.removeEvent();
                API.singerEvent.addEvent();
            }
            else {
                //屏蔽标记、激活三维控制
                API.singerEvent.removeEvent();
                API.baseEvent.addEvent();
            }
        return API;
    };
    
    //取消标记
    API.singerCancal = function(){
        API.singerRedo();
        //control.orbitCamera.enabledPose();
        world.stopRotate.enbale();
        API.singerEvent.removeEvent();
        container.removeEventListener("mousemove",API.singerEvent.draw,false);
        API.baseEvent.addEvent();
        return API;
    };
    
    //重做标记
    API.singerRedo = function(){
        singer.graphicLabeCancel()();
        return API;
    };
    
    //提取标记
    API.parseSinger = function(text){
        singer.parseSinger()(text);
        return API;
    };
    
    
    
    
    
    
    
    //剖切
    API.clip = function (boolean) {
        if(boolean){
            cliping.clippingView()(boolean);
            API.baseEvent.removeEvent();
        }else{
            cliping.clippingView()(boolean);
            API.baseEvent.addEvent();
        }
        return API;
    };
    
    
    //单个物体透明度设置
    API.opacity = function(value,ObjArr){
        if(ObjArr){
            ObjArr.forEach(function(arrObjName){
                var cc = world.modelGroup[arrObjName];
                    cc&&showOpacity.opacityControl(cc,value);
            })
        }else{
            if(!API.body)return;
                showOpacity.opacityControl(API.body,value);
        }
       
        return API;
    };
    
    //场景物体透明透明度设置
    API.MoreOpacity = function(value){
        if(value>1||value<0)return;
        world.modelArray.forEach(function(enm){
            showOpacity.opacityControl(enm,value);
        });
        return API;
    };
    
    //透明度恢复
    API.reopacity = function(){
       showOpacity.opacityRest();
        return API;
    };
    
    
    
    //模型单个显隐
    API.showHideModel = function(){
        if(!API.body)return;
        showOpacity.hoverControl()(API.body);
        return API;
        
    };
    
    //显示全部模型
    API.showModel = function () {
        showOpacity.showAll()();
        return API;
    };
    
    
    //更改颜色
    API.bodyColor = function (color,arrObj) {
        var obj = {},colors={},nColors={};
        if(arrObj!==undefined){
            arrObj.forEach(function (ems) {
                colors[ems] =  world.modelGroup[ems].material.color.clone().getHexString();
                obj.oldColor = colors;
                world.modelGroup[ems].material.color.set(color);
                nColors[ems] = world.modelGroup[ems].material.color.getHexString()
            })
        }
        else{
            if(API.body==undefined)return obj;
            colors[API.body.name]=  API.body.material.color.clone().getHexString();
            API.body.material.color.set(color);
            nColors[API.body.name]=API.body.material.color.getHexString()
        }
        obj.oldColor = colors;
        obj.newColor = nColors;
        return obj
    };
    
    
    //查找模型
    API.getNameModel=function(name){
        var objA;
        if(typeof (name)== "string"){
            objA = world.modelGroup[name];
        }
        else{
            if(name instanceof Array){
                objA = [];
                name.forEach(function (sname) {
                    objA.push(world.modelGroup[sname]);
                })
            }
        }
        return objA;
    };
    
    //创建模型组
    API.newGroup =function (arrObj,name) {
        var group = new THREE.Group();
            group.model = [];
        if(name==undefined)name = "GroupA";
        if(arrObj instanceof Array){
            arrObj.forEach(function (esa) {
                if(esa.isMesh){
                    group.add(esa.parent);
                }else{
                    if(typeof (esa)=="string"){
                        group.add(scope.getNameModel(esa).parent);
                        group.model.push(scope.getNameModel(esa));
                    }
                }
            })
        }else{
            if(typeof(arrObj)=="string"){
                group.add(scope.getNameModel(arrObj).parent);
                group.model.push(scope.getNameModel(arrObj));
            }
        }
        group.name = name;
        world.modelGroup[name]=group;
        world.scene.add(group);
        return group
    };
    
    
    //线框显示
    API.frame = function(){
        if(!API.body)return;
        showOpacity.showFrame()(API.body);
        return API;
    };
    
    //重置线框
    API.resetFrame = function () {
        showOpacity.resetFrame()();
        return API;
    };
    
    //查看平面图层
    API.viewPlane = function (boolean,value) {
        if(boolean){
            if(!material.path)return;
            if(value!==undefined){
                testfun(value);
            }else{
                material.planeParameter.position.set(5600,material.planeParameter.position.y,-1600);
               material.showPlaneImage(material.path);
            }
            world.renderer.localClippingEnabled = true;
        }else{
            material.removePlane();
            world.renderer.localClippingEnabled = false;
        }
        return API;
    };
    
    //隐藏平面图层
    API.hidePlane = function(boolean){
        material.hidePlaneImage()(boolean);
        return API;
    };
    
    //移除当前的平面图层
    API.removePlane = function () {
      material.removePlane();
        return API;
    };
    
    
    //更换Canvas背景色
    API.changeColor = function(color){
        world.scene.background = new THREE.Color(color);
        return API;
    };
    
    //更换鼠标习惯
    API.changeHabit = function(value){
        if(value == 0){
            world.camera.orbitControls.mouseButtons = { ORBIT: value, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };
        }else if(value == 2){
            world.camera.orbitControls.mouseButtons = { ORBIT: value, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.LEFT };
        }
        return API;
    };
    
    //隔离
    API.quarantine = function () {
        if(!API.body)return;
        API.opacity(1);
        var id = API.body.id;
        var i = 0;
        var targetObj = world.modelArray;
        for(; i<targetObj.length; i++){
            var target = targetObj[i].id;
            if(id !== target){
                showOpacity.opacityControl(targetObj[i],0.5);
            }
        }
        return API;
    };
    
    //重置场景
    API.reset = function(){
        
        //重置透明度
        showOpacity.opacityset(showOpacity.opacityData,showOpacity.opacityDataid);
        
        //显示所有的模型
        showOpacity.showAll()();
        
        //去除所有线框
        showOpacity.resetFrame()();
        
        //移除所有的平面图层
        material.removePlane();
        
        //视角重置
        cameraMark.initView()();
        
        //撤销当前的图层剖面调用
        API.viewPlane(false);
        return API;
    };
    
    
    
    
    //保存视角书签
    API.saveMark = function (name,callback) {
        return cameraMark.saveMark()(name,callback);
    };
    
    //提取视角书签
    API.parseMark = function (markJson) {
        cameraMark.parseMark()(markJson);
        return API;
    };
    
    //获取当前界面的缩略图
    API.image = function (value) {
       return world.screenShot(function(img){},value);
    };
    
    //构件闪烁
    API.twinkle = function (name,time,callback) {
        var object = world.modelGroup[""+name+""];
        if(object){
            var times = time || 210;
            var flag = false;
            var testing = pick;
            return function(){
                var twin = setInterval(function () {
                    flag = flag === false;
                    if(flag){
                        testing.showModelData(object);
                    }else{
                        testing.showModelData();
                    }
                },times);
                callback&&callback(twin);
            };
        }
        return API;
    };
    
    //计算模型尺寸
    API.scaleplate = function(name){
       
       var scale = {
           length: undefined,             //边界长度
           Parea: undefined,              //表平面
           volume: undefined,             //体积
           Harea: undefined,              //弯曲表面
           Tarea: undefined              //总面积
       },aobj;
       
        if(name!==undefined){
            aobj = scope.getNameModel(name);
        }else{
            if(!API.body)return;
            aobj = API.body;
        }
        
        //用于计算当前模型的几何数据属性。
        measure.compute(aobj,scale);
        
        return scale;
    };
    
    
    //模型分解
    API.dismantle = function(){
        disassemble.animations();
        return API;
    };
    
    //分解还原
    API.redismantle = function(){
        disassemble.resetModel(100);
        return API;
    };
    
    
    //层间滑动
    API.slide = function(value){
        var obeject = API.body;
        if(!obeject)return;
        disassemble.setPosition(obeject.parent,value,"ref");
        return API;
    };
    
    //层间滑动重置
    API.resetSlide = function(){
        disassemble.resetPosition();
        return API;
    };
    
    
    //模型贴图
    API.materialMap = function(value){
        var object = API.body;
        if(object == undefined)return;
        if(value){
            pick.lightModel(object);
            var materialObject = {
                materialArray:[],
                material:{}
            };
            material.textrueChange(materialObject,[value],function(text){
                material.materialManger(object,text);
            });
        }else{
            pick.lightModel(object,true);
            material.resetTextrue(object);
        }
        return API;
    };
 
    //模型加载
    API.load = function (value,nameIndex,type) {
        //缓存加载模型
        if(value !==undefined ){
            var path;
            if(value.path.length>0) path= value.path;
            else path =  [{
                reference: type|| "ifc",
                url: ""+value,
                talbe:nameIndex,
            }];
            cache.cacheFun({
                getFlag: true,
                keys: true,
                url: path,                  //后台数据接口
                localPlane: data.clipping,
                scene: world.scene,
                container: world,
                number: value.tableN,
                index: value.index,
            });
    
        }else{
            cache.cacheFun({
                getFlag: true,
                keys: true,
                url: data.modelURL,                  //本地数据接口
                localPlane: data.clipping,
                scene: world.scene,
                container: world,
                number: 0
            });
        }
        return API;
    };
    
    //模型数据
    API.modelDatas = function(name){
        var objs;
        if(!API.body){
            objs=scope.getNameModel(name);
        }else{
            objs=API.body;
        }
        var objModel = {
            poP:objs.position.toArray(),
            roT:objs.rotation.toArray(),
            scale:objs.scale.toArray(),
            name:objs.name,
            faces:objs.geometry.index.count/3,
            vec:objs.geometry.attributes.position.count/3,
        };
        return objModel
    };
    
    
    //模型属性自定义关联
    API.modelAtrr = {
        
        add: addattr.add,
        
        get: addattr.get,
        
        remove: addattr.remove,
        
        save: addattr.save
        
    };
    
    
    /**
     *
     * 初始化区域
     *
     **/
   
    
    
    
    
    //初始化各项参数
    API.start = function init(id,model){
        _init();
        /**
         *
         * 加载各个模块的功能
         *
         * */
    
        //加载场景
        world.init(id)(data);
        
        //加载鹰眼
        hawkeye.init(id,world.camera,cameraMove);
    
        //加载相机控制器(轨道相机)
        control.cameraOrbit(world.camera,hawkeye.container).enableZoom = false;
        control.cameraOrbit(world.camera,world.container);
        controleye.cameraOrbit(hawkeye.camera,hawkeye.container);
        controleye.cameraOrbit(hawkeye.camera,world.container);
        
        //漫游相机
        control.cameraView(world.viewCamera,world.scene);
    
        //设置拾取
        pick.init(world);
        
        //添加属性设置
        addattr.init(world);
    
        //加载相机移动
        cameraMove.init(world, control.orbitCamera);
    
        //初始化cache
        cache.init(data.indexedObject);
        
        // //缓存加载模型
        API.DB = cache;
        
        // API.load();
    
        //初始化测量数据
        measure.init(world.sceneHelper,pick,data.pointPictur);
    
        //初始化标记数据
        singer.init(world,pick,data.tageClass);
    
        //初始化剖面
        cliping.init(world,pick,data.clippingCube);
    
        //初始化材质更换
        material.init(world.scene,data.planImage,data.planeParameter);
    
        //初始化视角书签
        cameraMark.init(world);
    
        //初始化分解模型
        disassemble.init(world);
        
        //初始化框选
        region.init(world);
    
        //初始化Canvas
        container = world.container;
    
        //绑定测量事件
        API.measureEvent = {
            start:function (event){
                measure.mesure()(event);
            },
            end : function (event){
                //measure.measureLines()(event,Vm.showMeasureTip);
            }
        };
    
        //绑定标记事件
        API.singerEvent = {
        
            //鼠标摁下事件
            downClick: function (event){
                world.stopRotate.dispose();
                var flags = singer.graphic()(event);
                if(flags)container.addEventListener("mousemove",API.singerEvent.draw,false);
            
            },
        
            //鼠标抬起事件
            upClick: function (event){
                var designator = singer.endPoint;
                if(!designator){
                    singer.grapgraphicMove()(event);
                };
                container.removeEventListener("mousemove",API.singerEvent.draw,false);
               // Vm.showCalloutTip();
            },
        
            //显示标记
            show: function(value,className,callback) {
                //传入标记的内容
                singer.drawDiv(value,className);
            
                //显示标记
                singer.graphicShow()();
            
                //恢复三维控制
                if(!singer.flag)return;
                API.saveMark("singer",function (saveMark) {
                    var param = {
                        cameraMark:saveMark,
                        singer: singer.temporary
                    };
                    callback&&callback(param);
                
                });
                world.stopRotate.enbale();
                //control.orbitCamera.enabledPose();
                API.singerEvent.removeEvent();
                API.baseEvent.addEvent();
                container.removeEventListener("mousemove",API.singerEvent.draw,false);
            },
        
            //绘制标记线条
            draw: function (event){
                singer.grapgraphicMove()(event)
            },
        
            //添加基础操作
            addEvent:function(){
                container.addEventListener("mousedown",API.singerEvent.downClick,false);
                container.addEventListener("mouseup",API.singerEvent.upClick,false);
            },
        
            //移除基本操作
            removeEvent: function(){
                //屏蔽标记、激活三维控制
                container.removeEventListener("mousedown",API.singerEvent.downClick,false);
                container.removeEventListener("mouseup",API.singerEvent.upClick,false);
            }
        
        };
    
        //基础操作
        API.baseEvent = {
            addEvent: function(){
                container.addEventListener("mousedown",API.operationPick,false);
                container.addEventListener("mouseup",API.operationPick,false);
                container.addEventListener("dblclick",API.flyTo,false);
                region.start();
            },
            removeEvent: function(){
                container.removeEventListener("mousedown",API.operationPick,false);
                container.removeEventListener("mouseup",API.operationPick,false);
                container.removeEventListener("dblclick",API.flyTo,false);
                region.dispose();
            }
        };
    
        //渲染器更新
        world.updateFun.push(function (){
        
            //自由相机更新
            world.numberData = control.numberData;
            control.renderFreeCamera(control.viewCamera)();
            singer.tagFollow()();
            //初始化oject3D
            API.body = pick.temporary;
        
        });
    
        //添加基础事件
        API.baseEvent.addEvent();
        
        //禁止旋转
        world.stopRotate = {
           dispose: function(){
              control.orbitCamera.dispose();
              controleye.orbitCamera.dispose();
           },
           enbale: function(){
              control.orbitCamera.enabledPose();
              controleye.orbitCamera.enabledPose();
           }
        };
        
        //调用渲染器
        world.animation();
        return API;
    
    };
    
    //演示Or测试函数
        function testfun(value) {
            var objects = data.clippingTest;
            var pram = objects.picture[value];
            data.clipping[0] = objects.plan[value];
            material.planeParameter.position.set(pram.position.x,pram.position.y,pram.position.z);
            material.planeParameter.rotation.set(pram.rotation.x,pram.rotation.y,pram.rotation.z);
            var po = material.planeParameter;
                po.width=pram.width;po.height=pram.height;po.wrapS=po.wrapT=pram.wrapS;
            material.showPlaneImage(objects.picture[value].path);
        }
    
    
    return API;
});

